﻿var myDepart='/department/myDepart.do';   			//获取单位负责人，统计负责人，联系电话 的接口

/** 多部门、多年份查询指标接口 */
var getIndicatores='/report/query/depart/indicator.do';

//加载进度条
function load_jindutiao(datas){

    var datasLength=0;
    if(datas!=null){
        datasLength=datas.length;
    }
    /*
     * 计算上报进度
     */
    var count=0;
    if(datas!=null&&datasLength>0){
        for (var i = 0; i < datasLength; i++) {
            if(datas[i].status==5){
                count++;
            }
        }
    }

    var ratio=0;
    if(datasLength!=0){
        ratio=parseFloat((count/datasLength*100).toFixed(2));
    }
    $("#depNum").text(isNaN(datasLength)?0:datasLength);
    $("#depAlready").text(isNaN(count)?0:count);
    $("#depNot").text(isNaN(datasLength-count)?0:(datasLength-count));
    $("#depProportion").text(isNaN(ratio)?0:ratio+"%");

    $('#p').progressbar('setValue', isNaN(ratio)?0:ratio);
    var value = $('#p').progressbar('getValue');
    if (value < 100){
        if(value<=30){
            $(".progressbar-value .progressbar-text").css({"background-color":"red"});
        }else if (value<=60){
            $(".progressbar-value .progressbar-text").css("background-color","#ea8010");
        }else if (value<=80){
            $(".progressbar-value .progressbar-text").css({"background-color":"#00bb9c"});
        }else{
            $(".progressbar-value .progressbar-text").css("background-color","#1195db");
        }
    }
}

function loadYear(){
    $('#yearSelect').combobox({
        onLoadSuccess: function () {
            var nowYear = formatDate(new Date(), "yyyy");
            $("#yearSelect").combobox("select", nowYear-1);
        },
        onSelect: function(rec){
            query();
        }
    });
}

//汇总导出
function total_Excel(){
    var grid = $("#target_Grid_data");
    var rows=grid.datagrid("getRows");
    var name='汇总数据';
    var colums_all=grid.datagrid("options").columns;      		     //获得表格的所有列不包括冻结列
    var columses=[];
    var columss=[];
    for (var i = 0; i < colums_all[0].length; i++) {
        columss.push(colums_all[0][i]);
    }
    columses[0]=columss;
    var obj = $.ExportExcelDlg({
        HeadInfo: columses,    //表头栏
        RowInfo: rows,		   //数据航
        FooterInfo: grid.datagrid("getFooterRows"),
        RowStart: 1,		   //导出行位置
        ColumStart: 1,		   //导出列位置
        SheetName: name,
        MainTitle: { Displayname: name, Alignment: 'Center' },
        SaveName: name,
        Swf: 'ExportExcel.swf'
    });
    obj.ExportExcelDlg('open');
}

function getShowColumns() {

    var columns = [[
        {field:'ck',width:30,align:'center',checkbox:true},
        {field:'dname',title:'部门名称',width:80,align:'left'},
        {field:'year',title:'年份',width:20,align:'center'},
        {field:'mtime',title:'上报时间',width:35,sortable:'true',align:'center',
            formatter:function (value, row, index) {
                if(value!=null&&value!=undefined&&value!=''){
                    return formatterDate(new Date(value));
                }else{
                    return '';
                }
            }
        },
        {field:'editor',title:'上报人',width:30,align:'center'},
        {field:'status',title:'上报状态',width:30,sortable:'true',align:'center',
            formatter:function (value, row, index) {
                if(value<4&&value>0){
                    return '未上报';
                }else if(value==5){
                    return '已上报';
                }else if(value==auditState){
                    return '<span title="'+row.cancel+'">申请退回</span>';
                }else{
                    return '';
                }
            },
            styler: function(value,row,index){
                if (value == auditState){
                    return 'background-color:#ffee00;color:red;';
                }else if(value<4&&value>0){
                    return 'background-color:red;color:#fff;';
                }
            }
        },
        {field:'opration',title:'操作',width:40,align:'center',
            formatter:function (value, row, index) {
                var th = "<a style='color:blue' href='#' onclick='modifyStates("+row["departid"]+","+row["year"]+")'>批准退回</a>";
                if(row.status==auditState){
                    return th;
                }
                else{
                    return '';
                }
            }
        },
        {field:'maker',title:'填表人',width:30,align:'center'},
        {field:'cancel',title:'理由',width:50,align:'center'},
        {field:'charge',title:'单位负责人',width:30,align:'center'},
        {field:'author',title:'统计负责人',width:30,align:'center'},
        {field:'phone',title:'联系电话',width:50,align:'center'},
        {field:'email',title:'联系邮箱',width:50,align:'center'},
        {field:'address',title:'联系地址',width:50,align:'center'}
    ]]
    return columns;
}

function getHiteColumns() {

    var yearSelect=$("#yearSelect").combobox("getValue");
    if(yearSelect==null){
        yearSelect = formatDate(new Date(), "yyyy");
    }
    var yearLast=yearSelect-1;
    var showReportColumnsvalueYear = {

        "rtype" : {field:"rtype",title:'数据类型',width:80,
            formatter: function (value, row, index) {
                if(value==null||value==0){
                    return pipingLevel[0].text;
                }
                for(var i =0;i<pipingLevel.length;i++){
                    if(pipingLevel[i].value==value){
                        return pipingLevel[i].text;
                    }
                }
            },
            editor:{
                type:"combobox",
                options: {
                    data:pipingLevel,
                    valueField: "value",
                    textField: "text",
                    editable: true
                }
            }
        },
        "yearLast" : {field:yearLast+"",title:yearLast+"",width:92,align:'center',
            formatter: function (value, row, index) {

                // 数据上报的类型_每年的目标值_数值_显示数据展示时效果的规则_每年的备注
                var tempValue;
                if(value!=null && value.indexOf('_')!=-1){
                    tempValue = value.split('_')[2];
                }
                if(tempValue===null||tempValue==""||tempValue=="null"||tempValue=="NULL"){
                    return "";
                }else{
                    return tempValue;
                }
            }
        },
        "yearSelect" : {field:yearSelect,title:yearSelect,width:100,align:'center',
            editor : 'text',
            formatter: function (value, row, index) {

                // 数据上报的类型_每年的目标值_数值_显示数据展示时效果的规则_每年的备注
                var tempValue;
                if(value!=null && value.indexOf('_')!=-1){
                    tempValue = value.split('_')[2];
                }
                if(tempValue===null||tempValue==""||tempValue=="null"||tempValue=="NULL"){
                    return "";
                }else{
                    return tempValue;
                }
            }
        }
    }
    var reportShowColumns = [
        defineTableReportAllColumns["iname"],
        defineTableReportAllColumns["code"],
        defineTableReportAllColumns["unit"],
        defineTableReportAllColumns["places"],
        showReportColumnsvalueYear["yearLast"],
        showReportColumnsvalueYear["yearSelect"],
        showReportColumnsvalueYear["rtype"],
        defineTableReportAllColumns["sname"],
        defineTableReportAllColumns["memo"]
    ];
    return reportShowColumns;
}

//获取打印报表头部信息
function startPrint(){
    var formid=$("#formid").combobox("getValue");
    $("#rname").text("");
    $("#rnumber").text("");
    $("#rmaking").text("");
    $("#rcode").text("");
    $("#rexpire").text("");
    $("#ih3").text("");

    $.get(getReport, function(json){
        for (var i = 0; i < json.length; i++) {
            if(json[i].id==formid){
                $("#rname").text(json[i].name);
                $("#rnumber").text(json[i].number);
                $("#rmaking").text(json[i].making);
                $("#rcode").text(json[i].code);
                $("#rexpire").text(json[i].expire);
                $("#ih3").text(json[i].name);
            }
        }
        printMyDepart();
        print_excel();
    },'JSON')
}

function printMyDepart() {

    $.ajax({
        url: myDepart,
        async: false,//同步方式发送请求，true为异步发送
        type: "GET",
        dataType: "json",
        data: {},
        success: function (data) {
            // data = eval('(' + data + ')');
            if(data==null){
                $.messager.show({
                    title: '系统提示',
                    msg: '获取用户部门信息失败！',
                    timeout: 1500
                });
                return;
            }
            if(data['charge']!=null&&data['charge']!=undefined){
                $('.charge').text(data['charge']);
            }
            if(data['author']!=null&&data['author']!=undefined){
                $('.author').text(data['author']);
            }
            if(data['phone']!=null&&data['phone']!=undefined){
                $('.phone').text(data['phone']);
            }

            var time = new Date();
            reportDate = time.getFullYear()+"-"+(time.getMonth()+1)+"-"+time.getDate();
            $('.reportDate').text(reportDate);
        }
    });

    var reportPerson=$("#maker").val();     //填表人
    $('#makerPr').text(reportPerson)
}

function isContains(str, substr) {
    if(str==null||str=='undefined'){
        return false;
    }
    return str.toString().indexOf(substr) >= 0;
}


//根据部门获得指标信息方法
function getTargetBydepart(departId,page,pageSize){


    var formsid=$('#formid').combobox('getValue');

    departIds=departId;
    var yearSelect=$("#yearSelect").combobox("getValue");
    if(yearSelect==null){
        yearSelect = formatDate(new Date(), "yyyy");
    }
    var reportShowColumns = getHiteColumns();
    var years=yearSelect+","+(yearSelect-1);
    $.get(getIndicatores, {"departids":departId,"aimYear":yearSelect,"years":years,'indicatorids':-1,"formsid":formsid,"page":page,"pageSize":pageSize} ,function (data) {

        if(data.code==200){
            var datas=data['data'].results;
            var total=data['data'].size;
            var totalPage = Math.ceil(total / pageSize);
            var start = (page-1) * pageSize;
            if(datas==''||datas==null||datas==undefined||datas=='[]'||datas==[]){
                $('#target_Grid').datagrid({
                    data:[],
                });
                return;
            }
            var dataLength=datas.length;
            $('#target_Grid_data').datagrid({
                width: '100%',
                columns:[reportShowColumns],
                data:datas,
                pageNumber : page,// 显示数据列用
                pageSize : pageSize,
                pageList : [ 30, 500, 1000, 1500 ],
                pagination:true
            });
            var pg = $("#target_Grid_data").datagrid("getPager");
            $(pg).pagination({
                total: total,
                pageList : [ 30, 500, 1000, 1500 ],
                pageSize: pageSize,
                pageNumber: page,
                beforePageText: '第',
                afterPageText: '页    共 ' + totalPage + ' 页',
                displayMsg: '当前显示 ' + (start + 1) + '-' + (start + dataLength) + ' 条记录 共 ' + total + ' 条记录',
                onSelectPage: function (curPage, pageSize) {
                    getTargetBydepart(departIds,curPage,pageSize)
                },
                onChangePageSize: function (ps) {
                    pageSize = ps;
                }
            });
            try{window.parent.unmask();}catch(err){}
        }else{
            clearTGRID();
        }
    }, "json");
}

//指标列表无数据时清空处理
function clearTGRID(){
    $('#target_Grid').datagrid({
        data:blankLine("target_Grid",1)
    });
    var target_pg = $("#target_Grid").datagrid("getPager");
    $(target_pg).pagination({
        total: 0,
        pageList: [50,100,500],
        beforePageText: '第',
        afterPageText: '页    共 ' + 0 + ' 页',
        displayMsg: '当前显示' + 0 + '-' + 0 + ' 条记录 共 ' + 0 + ' 条记录',
    });
}

//---------打印显示报表的数据OK
function print_excel() {

    $("#addView_body_contents").empty();

    var yearSelect=$("#yearSelect").combobox("getValue");
    if(yearSelect==null){
        yearSelect = formatDate(new Date(), "yyyy");
    }
    var yearLast = yearSelect-1;
    var grid = $("#target_Grid_data");
    var rows=grid.datagrid("getRows");

    for (var i = 0; i < rows.length; i++) {
        var str="<tr>"+
            "<td style='text-align:left;padding-left:15px;border:1px solid;border-left:none;'>"+rows[i].iname+"</td>"+
            "<td style='border:1px solid;'>"+rows[i].code+"</td>"+
            "<td style='border:1px solid;'>"+rows[i].unit+"</td>"+
            "<td style='border:1px solid;'>"+rows[i].places+"</td>"+
            "<td style='width:50px;border:1px solid;'>"+getRvalue(rows[i][yearLast])+"</td>"+
            "<td style='width:50px;border:1px solid;'>"+getRvalue(rows[i][yearSelect])+"</td>"+
            // "<td style='border:1px solid;'>"+getRtype(rows[i][yearSelect])+"</td>"+
            "<td style='border:1px solid;'>"+rows[i].sname+"</td>"+
            "<td style='width:100px;border:1px solid;border-right:none;'>"+getRemark(rows[i][yearSelect])+"</td>"+
            "</tr>"
        var $row=$(str);
        $("#addView_body_contents").append($row);
    }
    $("#print_div").show();
    $("#print_div").jqprint();
    $("#print_div").hide();
}

function getRvalue(value) {
    if(value==null){
        return;
    }
    // value
    // 数据上报的类型_每年的目标值_数值_显示数据展示时效果的规则_每年的备注
    var valueSelect=null;
    if( isNaN(value) && value.indexOf('_')!=-1){
        valueSelect = value.split('_')[2];
    }
    return valueSelect;
}

function getRemark(value) {
    if(value==null){
        return;
    }
    // 数据上报的类型_每年的目标值_数值_显示数据展示时效果的规则_每年的备注
    var remark=null;
    if( isNaN(value) && value.indexOf('_')!=-1){
        remark = value.split('_')[4];
    }
    remark=(remark==undefined||remark==null)?'':remark;
    return remark;
}


function oncheckrows(index){

    var getSelected=$("#depart_Grid").datagrid('getSelected');
    var checkRow=$("#depart_Grid").datagrid('getChecked');

    if(index==0 &&(getSelected==null||getSelected=='undefined'||getSelected=="")){
        return;
    }
    //所勾选的部门id
    var departids="";
    for (var i = 0; i < checkRow.length; i++) {
        departids=departids+checkRow[i].departid+',';
    }

    var content = "<div id='target_Grid_data'></div>";
    $('#target_Grid_show').dialog({
        title: '指标列表',
        width:'95%',
        left:'1%',
        top:'5%',
        closable: true,
        cache: false,
        modal: true,
        inline:false,
        toolbar: [{
            text: '打印',
            iconCls: 'icon-print',
            handler: function(){
                startPrint();
            }
        },{
            text: '导出',
            iconCls: 'icon-excel',
            handler: function(){
                total_Excel();
            }
        }],
        content:content
    });
    getTargetBydepart(departids,page,pageSize);
}
